
import java.lang.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
import java.util.ArrayList;

public class GererItem extends JDialog implements ActionListener {

  private JLabel lNom;
  private JLabel lCat;
  private JTextField tNom;
  private JComboBox cbCat;
  private JButton bOk;
  private JButton bQuit;
  private Item i;
  private Container contenu;

  public GererItem(Item item) {
    super((JDialog) null, true);
    this.setLayout(null);
    this.setTitle("Modifier élément");
    this.i = item;
    this.lNom = new JLabel("Nom élément: ");
    this.lCat = new JLabel("Nom catégorie: ");
    this.tNom = new JTextField(this.i.getNom());

    //Affichage dynamique des catégorie
    ArrayList<Categorie> categs = null;
    try {
      categs = Categorie.chargerCategories();
    } catch (SQLException errUser) {
      JOptionPane.showMessageDialog(this, "Erreur dans le chargement des catégories \n" + errUser, "Erreur BDD", JOptionPane.ERROR_MESSAGE);
    }
    String[] listeCategs = new String[categs.size()];
    int b = 0;
    for (Categorie c : categs) {
      listeCategs[b] = c.getNom();
      b++;
    }
    this.cbCat = new JComboBox(listeCategs);
    this.cbCat.setMaximumRowCount(5);

    this.bOk = new JButton("Modifier");
    this.bOk.addActionListener(this);

    this.bQuit = new JButton("Annuler");
    this.bQuit.addActionListener(this);

    this.contenu = this.getContentPane();

    this.contenu.add(this.lNom);
    this.contenu.add(this.lCat);
    this.contenu.add(this.tNom);
    this.contenu.add(this.cbCat);
    this.contenu.add(this.bOk);
    this.contenu.add(this.bQuit);

    this.lNom.setBounds(10, 10, 100, 20);
    this.tNom.setBounds(130, 10, 100, 20);
    this.lCat.setBounds(10, 40, 100, 20);
    this.cbCat.setBounds(130, 40, 100, 20);
    this.bOk.setBounds(10, 70, 100, 20);
    this.bQuit.setBounds(130, 70, 100, 20);

    this.setBounds(20, 20, 300, 200);
    this.setVisible(true);
    this.setResizable(false);
  }

  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == bOk) {
      String nomEl = (String) this.tNom.getText();
      String nomCat = (String) this.cbCat.getSelectedItem();
      try {
        this.i.setNom(nomEl);
        try {
          this.i.setCategorie(Categorie.getCategorie(nomCat));
          JOptionPane.showMessageDialog(this, "Modification réussie", "Modifier un élément", JOptionPane.INFORMATION_MESSAGE);
          this.dispose();
        } catch (SQLException evn) {
          JOptionPane.showMessageDialog(this, "Impossible de modifier la catégorie", "Modifier un élément", JOptionPane.ERROR_MESSAGE);
        }
      } catch (SQLException evt) {
        JOptionPane.showMessageDialog(this, "Impossible de modifier le nom", "Modifier un élément", JOptionPane.ERROR_MESSAGE);
      }
    }
    if (e.getSource() == bQuit) {
      this.dispose();
    }
  }
}
